# This file is used to create a login blueprint for the flask application.
# The blueprint is used to handle the login functionality of the application.


from flask import Blueprint
from flask import request
from flask import jsonify
import psycopg2.extras
from settings import *
from db_utils.postgresql_connection import PostgreSQLConnection
from db_utils.repositories.device_data_table import DeviceDataTable
from db_utils.repositories.devices_table import DevicesTable
from wx_modules.wx_user_device_bind import WxUserDeviceBind
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

wx_device_blueprint = Blueprint('wx_device_blueprint', __name__)


@wx_device_blueprint.route('/bind_device', methods=['POST'])
def bind_device():
    # Get the required arguments from the request
    user_id = request.form.get('user_id')
    device_code = request.form.get('device_code')

    # Check if the required arguments are present
    if not user_id or not device_code:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "user_id and device_code are required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSQLConnection() as (conn, cur):

        # 获取设备ID

        devices_table = DevicesTable(conn, cur)

        device_result = devices_table.get_device_by_code(device_code)

        if not device_result:

            return {"status": -1, "errorCode": 1002, "errorMsg": "Device not found", "resultBody": None}

        device_id = device_result['id']


        wx_user_device_bind = WxUserDeviceBind(conn, cur)

        # 查询绑定关系是否存在
        bind_result = wx_user_device_bind.query_bind_by_device_id_user_id(device_id, user_id)

        if bind_result:

            wx_user_device_bind.update_bind_status(user_id, device_id, 'bind')

            args_success = {
                "status": 1,
                "errorCode": None,
                "errorMsg": None,
                "resultBody":  "Device bound successfully"
            }

            return jsonify(args_success)
        
        else:
        
            res, msg = wx_user_device_bind.insert_bind(user_id, device_id)

            if not res:
                args_error = {
                    "status": -1,
                    "errorCode": 1002,
                    "errorMsg": msg,
                    "resultBody": None
                }

            args_success = {
                "status": 1,
                "errorCode": None,
                "errorMsg": None,
                "resultBody":  "Device bound successfully"
            }

            return jsonify(args_success)
    

@wx_device_blueprint.route('/unbind_device', methods=['POST'])
def unbind_device():
    # Get the required arguments from the request
    user_id = request.form.get('user_id')
    device_id = request.form.get('device_id')

    # Check if the required arguments are present
    if not user_id or not device_id:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "user_id and device_id are required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSQLConnection() as (conn, cur):

        wx_user_device_bind = WxUserDeviceBind(conn, cur)

        wx_user_device_bind.update_bind_status(user_id, device_id, 'unbind')

        args_success = {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,                
            "resultBody":  "Device unbound successfully"
        }

        return jsonify(args_success)
        

@wx_device_blueprint.route('/query_bind_devices', methods=['POST'])
def query_bind_devices():
    # Get the required arguments from the request
    user_id = request.form.get('user_id')
    bind_status= request.form.get('bind_status', 'bind')

    # Check if the required arguments are present
    if not user_id:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "user_id is required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSQLConnection() as (conn, cur):

        wx_user_device_bind = WxUserDeviceBind(conn, cur)

        # 查询绑定关系
        bind_result = wx_user_device_bind.query_bind_by_user_id(user_id, bind_status)
        
        return {"status": 1, "errorCode": None, "errorMsg": None, "resultBody": bind_result}
    

@wx_device_blueprint.route('/delete_bind', methods=['POST']) # 物理删除绑定关系
def delete_bind():
    # Get the required arguments from the request
    user_id = request.form.get('user_id')
    device_id = request.form.get('device_id')

    # Check if the required arguments are present
    if not user_id or not device_id:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "user_id and device_id are required",
            "resultBody": None

        }

        return jsonify(args_error)

    with PostgreSQLConnection() as (conn, cur):

        wx_user_device_bind = WxUserDeviceBind(conn, cur)
        wx_user_device_bind.delete_bind(user_id, device_id)

        return {"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "Bind deleted successfully"}
    

# # 获取设备数据
#    def get_device_data(self, device_id=None, data_direction=None, date_start=None, date_end=None, limit=20, offset=0):
@wx_device_blueprint.route('/query_device_data', methods=['POST'])
def query_device_data():
    # Get the required arguments from the request
    device_id = request.form.get('device_id')
    date_start = request.form.get('date_start')
    date_end = request.form.get('date_end')
    limit = request.form.get('limit', default=5, type=int)
    offset = request.form.get('offset', default=0, type=int)

    data_direction = "up"

    # Check if the required arguments are present
    if not device_id :
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "device_id is required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSQLConnection() as (conn, cur):

        device_data_table = DeviceDataTable(conn, cur)

        # 查询设备数据
        device_data_result = device_data_table.get_device_data(device_id, data_direction, date_start, date_end, limit, offset)
        
        return {"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_data_result}









